package cn.echogo.framework.location;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

import com.google.android.maps.GeoPoint;

public class LocationUtil {
	
	public static Location getLocation(Context context) {
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

		// GPS定位
		Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (location != null) {
			System.out.println("[GPS] :: ");
		}
		// 网络定位（测试通过）
		location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		if (location != null) {
			System.out.println("[NET] :: ");
		}
		return location;
	}

	public static void requestLocation(Context context, String provider, LocationListener listener) {
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(provider, 3000, 0, listener);
	}
	
	public static GeoPoint getGeoPointByLocation(Location location) {
		GeoPoint point = null;
		try {
			if (location != null) {
				double geoLatitude = location.getLatitude() * 1E6;
				double getLongitude = location.getLongitude() * 1E6;
				point = new GeoPoint((int) geoLatitude, (int) getLongitude);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return point;
	}

	public static Address getAddressByGeoPoint(Context context, GeoPoint point) {
		Address result = null;
		if (point != null) {
			Geocoder gc = new Geocoder(context, Locale.CHINA);
			double geoLatitude = (int) point.getLatitudeE6() / 1E6;
			double geoLongitude = (int) point.getLongitudeE6() / 1E6;
			try {
				List<Address> listAddress = gc.getFromLocation(geoLatitude, geoLongitude, 1);
				if (listAddress.size() > 0) {
					result = listAddress.get(0);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return result;
	}
	
	public static String getAddressString(Address address) {
		StringBuffer sb = new StringBuffer();
		sb.append(address.getAddressLine(0));		//中国
		sb.append(address.getAddressLine(1));		//广东省广州市天河区
		sb.append(address.getThoroughfare());		//东燕街
		return sb.toString();
	}
	

}
